package com.migo.utils;

import java.io.*;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Wes on 2019/2/1.
 */
public class ZipUtils {
    /**
     * 使用GBK编码可以避免压缩中文文件名乱码
     */
    private static final String CHINESE_CHARSET = "GBK";

    /**
     * 文件读取缓冲区大小
     */
    private static final int CACHE_SIZE = 1024;

    private ZipUtils() {
        // 私用构造主法.因为此类是工具类.
    }

    /**
     * <p>
     * 压缩文件
     * </p>
     *
     * @param sourceFolder
     *            需压缩文件 或者 文件夹 路径
     * @param zipFilePath
     *            压缩文件输出路径
     * @throws Exception
     */
    public static void zip(String sourceFolder, String zipFilePath) throws Exception {
        System.out.println("开始压缩 [" + sourceFolder + "] 到 [" + zipFilePath + "]");
        OutputStream out = new FileOutputStream(zipFilePath);
        BufferedOutputStream bos = new BufferedOutputStream(out);
        org.apache.tools.zip.ZipOutputStream zos = new org.apache.tools.zip.ZipOutputStream(bos);
        // 解决中文文件名乱码
        zos.setEncoding(CHINESE_CHARSET);
        File file = new File(sourceFolder);
        String basePath = null;
        if (file.isDirectory()) {
            basePath = file.getPath();
        } else {
            basePath = file.getParent();
        }
        zipFile(file, basePath, zos);
        zos.closeEntry();
        zos.close();
        bos.close();
        out.close();
        System.out.println("压缩 [" + sourceFolder + "] 完成！");
    }

    /**
     * <p>
     * 压缩文件
     * </p>
     *
     * @param sourceFolders
     *            一组 压缩文件夹 或 文件
     * @param zipFilePath
     *            压缩文件输出路径
     * @throws Exception
     */
    public static void zip(String[] sourceFolders, String zipFilePath) throws Exception {
        OutputStream out = new FileOutputStream(zipFilePath);
        BufferedOutputStream bos = new BufferedOutputStream(out);
        org.apache.tools.zip.ZipOutputStream zos = new org.apache.tools.zip.ZipOutputStream(bos);
        // 解决中文文件名乱码
        zos.setEncoding(CHINESE_CHARSET);

        for (int i = 0; i < sourceFolders.length; i++) {
            System.out.println("开始压缩 [" + sourceFolders[i] + "] 到 [" + zipFilePath + "]");
            File file = new File(sourceFolders[i]);
            String basePath = null;
            basePath = file.getParent();
            zipFile(file, basePath, zos);
        }

        zos.closeEntry();
        zos.close();
        bos.close();
        out.close();
        System.out.println("压缩 " + (sourceFolders) + " 完成！");
    }

    /**
     * <p>
     * 递归压缩文件
     * </p>
     *
     * @param parentFile
     * @param basePath
     * @param zos
     * @throws Exception
     */
    private static void zipFile(File parentFile, String basePath, org.apache.tools.zip.ZipOutputStream zos)
            throws Exception {
        File[] files = new File[0];
        if (parentFile.isDirectory()) {
            files = parentFile.listFiles();
        } else {
            files = new File[1];
            files[0] = parentFile;
        }
        String pathName;
        InputStream is;
        BufferedInputStream bis;
        byte[] cache = new byte[CACHE_SIZE];
        for (File file : files) {
            if (file.isDirectory()) {
                System.out.println("目录：" + file.getPath());

                basePath = basePath.replace('\\', '/');
                if (basePath.substring(basePath.length() - 1).equals("/")) {
                    pathName = file.getPath().substring(basePath.length()) + "/";
                } else {
                    pathName = file.getPath().substring(basePath.length() + 1) + "/";
                }

                zos.putNextEntry(new org.apache.tools.zip.ZipEntry(pathName));
                zipFile(file, basePath, zos);
            } else {
                pathName = file.getPath().substring(basePath.length());
                pathName = pathName.replace('\\', '/');
                if (pathName.substring(0, 1).equals("/")) {
                    pathName = pathName.substring(1);
                }

                System.out.println("压缩：" + pathName);

                is = new FileInputStream(file);
                bis = new BufferedInputStream(is);
                zos.putNextEntry(new org.apache.tools.zip.ZipEntry(pathName));
                int nRead = 0;
                while ((nRead = bis.read(cache, 0, CACHE_SIZE)) != -1) {
                    zos.write(cache, 0, nRead);
                }
                bis.close();
                is.close();
            }
        }
    }

    /**
     * 解压zip文件
     *
     * @param zipFileName
     *            待解压的zip文件路径，例如：c:\\a.zip
     *
     * @param outputDirectory
     *            解压目标文件夹,例如：c:\\a\
     */
    public static void unZip(String zipFileName, String outputDirectory) throws Exception {
        System.out.println("开始解压 [" + zipFileName + "] 到 [" + outputDirectory + "]");
        org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(zipFileName);

        try {

            Enumeration<?> e = zipFile.getEntries();

            org.apache.tools.zip.ZipEntry zipEntry = null;

            createDirectory(outputDirectory, "");

            while (e.hasMoreElements()) {

                zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();

                System.out.println("解压：" + zipEntry.getName());

                if (zipEntry.isDirectory()) {

                    String name = zipEntry.getName();

                    name = name.substring(0, name.length() - 1);

                    File f = new File(outputDirectory + File.separator + name);

                    f.mkdir();

                    System.out.println("创建目录：" + outputDirectory + File.separator + name);

                } else {

                    String fileName = zipEntry.getName();

                    fileName = fileName.replace('\\', '/');

                    if (fileName.indexOf("/") != -1) {

                        createDirectory(outputDirectory, fileName.substring(0, fileName.lastIndexOf("/")));

                        fileName = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());

                    }

                    File f = new File(outputDirectory + File.separator + zipEntry.getName());

                    f.createNewFile();

                    InputStream in = zipFile.getInputStream(zipEntry);

                    FileOutputStream out = new FileOutputStream(f);

                    byte[] by = new byte[1024];

                    int c;

                    while ((c = in.read(by)) != -1) {

                        out.write(by, 0, c);

                    }

                    in.close();

                    out.close();

                }

            }
            System.out.println("解压 [" + zipFileName + "] 完成！");

        } catch (Exception ex) {

            System.out.println(ex.getMessage());

        } finally {
            zipFile.close();
        }

    }

    /**
     * 创建目录
     *
     * @author hezhao
     * @Time 2017年7月28日 下午7:10:05
     * @param directory
     * @param subDirectory
     */
    private static void createDirectory(String directory, String subDirectory) {

        String dir[];

        File fl = new File(directory);

        try {

            if (subDirectory == "" && fl.exists() != true) {

                fl.mkdir();

            } else if (subDirectory != "") {

                dir = subDirectory.replace('\\', '/').split("/");

                for (int i = 0; i < dir.length; i++) {

                    File subFile = new File(directory + File.separator + dir[i]);

                    if (subFile.exists() == false)

                        subFile.mkdir();

                    directory += File.separator + dir[i];

                }

            }

        } catch (Exception ex) {

            System.out.println(ex.getMessage());

        }

    }

    /**
     * 无需解压直接读取Zip文件和文件内容
     *
     * @author hezhao
     * @Time 2017年7月28日 下午3:23:10
     * @param file
     *            文件
     * @throws Exception
     */
    public static void readZipFile(String file) throws Exception {
        java.util.zip.ZipFile zipFile = new java.util.zip.ZipFile(file);
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        java.util.zip.ZipInputStream zin = new java.util.zip.ZipInputStream(in);
        java.util.zip.ZipEntry ze;
        while ((ze = zin.getNextEntry()) != null) {
            if (ze.isDirectory()) {
            } else {
                System.out.println("file - " + ze.getName() + " : " + ze.getSize() + " bytes");
                long size = ze.getSize();
                if (size > 0) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(zipFile.getInputStream(ze)));
                    String line;
                    while ((line = br.readLine()) != null) {
                        System.out.println(line);
                    }
                    br.close();
                }
                System.out.println();
            }
        }
        zin.closeEntry();
    }


    /**
     * 遍历文件夹-查找文件及目录
     *
     * @param path
     */
    public static Map<String, String> getFileDirOrName(String path, Map<String, String> map) {
        Map<String, String> fileMap = map;
        File dirFile = new File(path);
        if (dirFile.exists()) {
            File[] files = dirFile.listFiles();
            if (files != null) {
                for (File fileChildDir : files) {
                    if (fileChildDir.isDirectory()) {
                        // 通过递归的方式,可以把目录中的所有文件全部遍历出来
                        getFileDirOrName(fileChildDir.getAbsolutePath(),fileMap);
                    }
                    if (fileChildDir.isFile()) {
                        File file = new File(fileChildDir.getAbsolutePath());
                        String strParentDirectory = file.getParentFile().getName();
                        String strPath = file.getParent()+File.separator+fileChildDir.getName();
                        fileMap.put(strPath, strParentDirectory);
                    }
                }
            }
        } else {
            System.out.println("你想查找的文件不存在");
        }
        return fileMap;
    }

    /**
     * 遍历文件夹-查找文件及目录
     *
     * @param path
     */
    public static Map<String, String> checkFileDirOrName(String path) {
        Map<String, String> fileMap = new HashMap<>();
        File dirFile = new File(path);
        if (dirFile.exists()) {
            File[] files = dirFile.listFiles();
            if (files != null) {
                for (File fileChildDir : files) {
                    // 输出文件名或者文件夹名
                    System.out.println(fileChildDir.getName());
                    // 解压zip文件
                    // uzipFile(path,fileChildDir.getName());
                    if (fileChildDir.isDirectory()) {
                        // System.out.println(" : 此为目录名");
                        // 通过递归的方式,可以把目录中的所有文件全部遍历出来
                        checkFileDirOrName(fileChildDir.getAbsolutePath());
                    }
                    if (fileChildDir.isFile()) {
                        System.out.println(" :  此为文件名");
                        File file = new File(fileChildDir.getAbsolutePath());
                        String strParentDirectory = file.getParentFile().getName();
                        fileMap.put(fileChildDir.getName(), file.getParent());
                        System.out.println("===文件的上级目录为 : " + strParentDirectory);
                    }
                }
            }
        } else {
            System.out.println("你想查找的文件不存在");
        }
        return fileMap;
    }

    /**
     * 查找zip文件进行解压
     *
     * @param path
     * @param fileName
     */
    public static void uzipFile(String path, String fileName) {
        try {
            String filePath = path + "/" + fileName;
            String dirPath = path + "/" + fileName.substring(0, fileName.indexOf(".zip"));
            if (fileName.contains(".zip")) {
                unZip(filePath, dirPath);
                File file = new File(dirPath);
                file.delete();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
